using System.Collections.Generic;
using ArmyAnt.ProcessController;
using PlayMyLife.Events;
using PlayMyLife.View.Components;
using PlayMyLife.ViewCommon;
using PlayMyLife.ViewModel;

using UnityEngine;

namespace PlayMyLife.View {
    public class StartScene : MonoBehaviour {
        [SerializeField] private RectTransform[] panelRoots;
        [SerializeField] private EventMgr eventMgr;
        [Space]
        [SerializeField] private GameObject prefab_startPanel;
        [SerializeField] private GameObject prefab_preparationPanel;
        [SerializeField] private GameObject prefab_gameMainPanel;
        [Space]
        [SerializeField] private TextAsset json_eventConfig;
        [SerializeField] private TextAsset json_skillConfig;

        private void Awake() {
            panelPrefabs.Add(PanelType.StartPanel, prefab_startPanel);
            panelPrefabs.Add(PanelType.PreparationPanel, prefab_preparationPanel);
            panelPrefabs.Add(PanelType.GameMainPanel, prefab_gameMainPanel);

            eventMgr.Listen(DirectorEvent.ShowPanel, OnShowPanel);
            eventMgr.Listen(DirectorEvent.ClosePanel, OnClosePanel);
        }

        private void Start() {
            GameViewManager.Init(eventMgr, json_eventConfig.text, json_skillConfig.text);
        }

        private void OnDestroy() {
            eventMgr.Unlisten(DirectorEvent.ShowPanel, OnShowPanel);
            eventMgr.Unlisten(DirectorEvent.ClosePanel, OnClosePanel);
        }

        private void OnShowPanel(IEventManager<DirectorEvent>.IEventArgs e) {
            if(e is EventArgs_ShowPanel args) {
                FormBase panel;
                if(!openedPanels.TryGetValue(args.Panel, out panel)) {
                    panel = Instantiate(panelPrefabs[args.Panel]).GetComponent<FormBase>();
                    openedPanels.Add(args.Panel, panel);
                }
                panel.Arguments = args;
                panel.Open(panelRoots[(int)args.Layer]);
            }
        }

        private void OnClosePanel(IEventManager<DirectorEvent>.IEventArgs e) {
            if(e is EventArgs_ClosePanel args) {
                if(openedPanels.TryGetValue(args.Panel, out var panel)) {
                    panel.Close();
                }
            }
        }

        private readonly Dictionary<PanelType, GameObject> panelPrefabs = new();
        private readonly Dictionary<PanelType, FormBase> openedPanels = new();
    }
}
